

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.cache.Cache;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ls.fw.token.annotation.RequireToken;

/**
 * This class is used as an interceptor for token validation. If token is not
 * valid set error to http request.
 * 
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = Logger.getLogger(TokenInterceptor.class);
    public static final String TOKEN = "_token";
//    @Autowired
    private org.springframework.cache.CacheManager cacheManager;

    private String tokenName = TOKEN;
    private String cacheName = "tokens";
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean valid = true;

        HandlerMethod method = (HandlerMethod) handler;

        RequireToken annotation = method.getMethodAnnotation(RequireToken.class);
        if (annotation != null) {
        	valid = false;
            String token = request.getParameter(tokenName);
            if(org.apache.commons.lang3.StringUtils.isBlank(token)){
            	token = request.getHeader(tokenName);
            }
            logger.info("token in the request <" + token + ">.");
            Cache cache = cacheManager.getCache(cacheName);
            if (StringUtils.isEmpty(token)) {
                valid = false;
                logger.info("token not found in the request.");
            } else if (!StringUtils.isEmpty(token) && cache.get(token) != null && !token.equals(cache.get(token).get())) {
                valid = false;
                logger.info("token in the cache <" + cache.get(token) == null ? "" : cache.get(token).get() + ">.");
            } else {
            	valid = true;
//                if (annotation.remove()) {
//                    cache.evict(token);
//                }
            }

            if (!valid) {
                logger.info("token is not valid , set error to request");
                request.setAttribute("error", "invalid token");
                // response.sendRedirect(request.getContextPath() +
                // "/error.htm");
            }
        }

        return valid;
    }

	public org.springframework.cache.CacheManager getCacheManager() {
		return this.cacheManager;
	}

	public void setCacheManager(org.springframework.cache.CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	public String getCacheName() {
		return cacheName;
	}

	public void setCacheName(String cacheName) {
		this.cacheName = cacheName;
	}

	public String getTokenName() {
		return tokenName;
	}

	public void setTokenName(String tokenName) {
		this.tokenName = tokenName;
	}

}
